package learningThread.threadPool.reject;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 将"线程池的拒绝策略"由DiscardPolicy修改为CallerRunsPolicy之后，当有任务添加到线程池被拒绝时，
 * 线程池会将被拒绝的任务添加到"线程池正在运行的线程"中取运行。
 */
public class TestCallerRunsPolicy {

    public static final int THREAD_SIZE = 1;

    public static final int CAPACITY = 1;

    public static void main(String[] args) {
        ThreadPoolExecutor pool = new ThreadPoolExecutor(THREAD_SIZE, THREAD_SIZE,
                0, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(CAPACITY));


        pool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

        TestCallerRunsPolicy testAborstPolicy = new TestCallerRunsPolicy();

        // 新建10个任务，并将它们添加到线程池中。
        for (int i = 0; i < 10; i++) {
            TestCallerRunsPolicy.MyRunnable myrun =testAborstPolicy.new MyRunnable("task-"+i);
            //pool.execute(myrun);
            pool.submit(myrun);
        }

        // 关闭线程池
        pool.shutdown();
    }

    class MyRunnable implements Runnable {
        String name;

        public MyRunnable(String s) {
            this.name = s;
        }

        @Override
        public void run() {
            System.out.println(this.name + "is running");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
